package com.sense.kukoo.common.wiget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import com.google.android.material.tabs.TabLayout
import com.sense.kukoo.common.R
import com.sense.kukoo.common.utils.ApplicationContext

class MediaSettingTabLayout: TabLayout {

    private val TAG: String = javaClass.simpleName
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private val mCustomViews: ArrayList<View> = arrayListOf()
    private var mOnTabListener: OnTabListener? = null
    private lateinit var mTitles: Array<String>
    private var mCaculateWidth = -1

    interface OnTabListener {
        fun onTabListener(position: Int)
    }

    fun setOnTabListener(onTabListener: OnTabListener?) {
        mOnTabListener = onTabListener
    }

    fun init(titles: Array<String>) {
        mTitles = titles
        //
        mCustomViews.clear()
        mTitles.forEachIndexed { index, s ->
            val tab = newTab()
            addTab(tab, index)
            tab.setCustomView(R.layout.common_item_tab_media_setting)
            tab.customView?.let {
                mCustomViews.add(it)
                val tv_item_tab_text = it.findViewById<TextView>(R.id.tv_item_tab_text)
                tv_item_tab_text.text = mTitles[index]
            }
        }
        //
        this.addOnTabSelectedListener(object : OnTabSelectedListener {

            override fun onTabSelected(tab: Tab) {
                tab.customView?.let {
                    mOnTabListener?.onTabListener(tab.position)
                }
            }

            override fun onTabUnselected(tab: Tab) {
                tab.customView?.let{}
            }

            override fun onTabReselected(tab: Tab) {}
        })
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        if(mCaculateWidth != width){
            mCaculateWidth = width
            val size = if(mCustomViews.size > 0) mCustomViews.size else 1
            val childWidth = mCaculateWidth / size - ApplicationContext.dp2px(8F)
            mCustomViews.forEachIndexed { index, view ->
                val layoutParams = view.layoutParams
                layoutParams.width = childWidth
                view.layoutParams = layoutParams
            }
        }
    }

}